import 'dart:async';
import 'dart:io';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/util/media_util.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/mine/drag/drag_like.dart';
import 'package:flutter/material.dart';
import 'package:flutter_plugin_record/index.dart';
import 'package:svgaplayer_flutter/player.dart';

class MineRecordPage extends StatefulWidget {

  @override
  _MineRecordPageState createState() => _MineRecordPageState();
}

class _MineRecordPageState extends State<MineRecordPage> {

  bool isrecord = false;

  _upload(BuildContext context,String path) {
    if(path == null) {
      AlertTool.showToast("请录制语音");
      return;
    }
    File temp = File(path);
    Networktool.uploadImage(API.signvoice, temp, (data){
      AlertTool.showToast("上传成功");
      temp.deleteSync();
      if(data != null)SharedUserInfo.saveData(data);
      Navigator.of(context).pop(true);
    },
    fail: (msg) => AlertTool.showToast(msg),
    );
  }

  Widget _createRecordBack(Size size) {
    if(isrecord) {
      return Positioned(
        bottom: 0,
        child: Opacity(
          opacity: 0.7,
          child: Image.asset("assets/gif/play.gif", width: size.width, height: 400,fit: BoxFit.fill,)
          // child: Container(
          //   width: size.width,
          //   height: 400,
          //   child: SVGASimpleImage(assetsName: "assets/gif/yinlang.svga",),
          // ),
        )
      );
    } else {
      return Positioned(
              bottom: 0,
              child: Image.asset("assets/yinglang2.png",width: size.width,fit: BoxFit.fitHeight),
            );
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Image.asset("assets/fanhui.png"),
          onPressed: (){
            MediaUtil.instance.stopPlayAudio();
            Navigator.of(context).pop();
          },
        ),
        centerTitle: true,
        title: Text("录制语音"),
      ),
      body: SafeArea(
        bottom: false,
        maintainBottomViewPadding: true,
        child: Stack(
          children: [
            Image.asset("assets/eg.png", width: size.width, height: size.height,fit: BoxFit.fill,),
            _createRecordBack(size),
            Container(
                padding: const EdgeInsets.only(top: 24, left: 25),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("台词卡片", style: instanceTextStyle(17, APP_font_black),),
                    SizedBox(height: 10,),
                    Container(
                      width: size.width,
                      height: size.height * 0.6,
                      padding: const EdgeInsets.only(left: 12, right: 37, bottom: 80),
                      child: DragLikePage(),
                    )
                  ],
                )
              ),
            Positioned(
              bottom: 48,
              child: Container(
                width: size.width,
                child: XMineRecordVoiceWidget(onRecordFinish: (path, duration){
                    _upload(context, path);
                  },
                  onRecordAction: (val){
                    setState(() {
                      isrecord = val;
                    });
                  },
                ),
              )
            ),
          ],
        ),
      ),
    );
  }
}

class XMineRecordVoiceWidget extends StatefulWidget {

  final Function(String path, int duration) onRecordFinish;
  final int mintime;
  final String noticelabel;
  final Function(bool isrecord) onRecordAction;

  const XMineRecordVoiceWidget({Key key, 
    this.onRecordFinish,
    this.mintime = 5,
    this.noticelabel = "长按录音\n录音时间不得少于5s哦～",
    this.onRecordAction
  }) : super(key: key);


  @override
  _XCommentVoiceWidgetState createState() => _XCommentVoiceWidgetState();
}

class _XCommentVoiceWidgetState extends State<XMineRecordVoiceWidget> {

  bool isselected = false;
  bool isrecord = false;
  File _file;
  bool isupadte = false;
  Timer _timer;
  int voiceLength = 30;
  int recordLength = 0; // 录制时长
  String voicestr = "00:00";
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _stopTimer();
    if(_file != null) _deleteFile();
    super.dispose();
  }

   _beginTimer() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if(voiceLength == 1) {
        _recordCallback(false);
        _stopTimer();
        voiceLength = 30;
        recordLength = 30;
        setState(() {
          voicestr = "00:30";
        });
      } else {
        voiceLength -= 1;
        int t = 30 - voiceLength;
        _changeTime(t);
      }
    });
  }

  _playTimer(int maxtime) {
    int temp = maxtime;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if(maxtime == 1) {
        _stopTimer();
        _changeTime(temp);
      } else {
        maxtime -= 1;
        int t = temp - maxtime;
        _changeTime(t);
      }
    });
  }

  void _changeTime(int time) {
    final t = time.toString();
    if(t.length == 1) {
      setState(() {
        voicestr = "00:0" + t;
      });
    } else {
      setState(() {
        voicestr = "00:" + t;
      });
    }
  }

  _stopTimer() {
    voiceLength = 30;
    _timer?.cancel();
    _timer = null;
  }

  _deleteFile() {
    String path = MediaUtil.instance.getCorrectedLocalPath(_file.path);
    File file = File(path);
    if (file != null && file.existsSync()) {
      file.deleteSync();
    }
  }

  _recordCallback(bool isrecord) {
    if(widget.onRecordAction != null) widget.onRecordAction(isrecord);
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      alignment: Alignment.center,
      child: Stack(
        children: [
          Offstage(
            offstage: isrecord,
            child: Column(
              children: [
                Offstage(
                  offstage: !isselected,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 7),
                    margin: const EdgeInsets.only(top: 12),
                    decoration: BoxDecoration(
                      color: APP_main_color,
                      borderRadius: BorderRadius.circular(20)
                    ),
                    child: Text(voicestr, style: instanceTextStyle(14, Colors.white),),
                  ),
                ),
                GestureDetector(
                  onLongPress: (){
                    setState(() {
                      isselected = !isselected;
                    });
                    _recordCallback(true);
                    MediaUtil.instance.startRecordAudio();
                    _beginTimer();
                  },
                  onLongPressUp: (){
                    _recordCallback(false); // 停止gif播放
                    int t = 30 - voiceLength;// 最大录音为30秒
                    if(t < widget.mintime) {
                      setState(() {
                        isrecord = false;
                        isselected = false;
                        voicestr = "00:00";
                      });
                    } else {
                      recordLength = t;
                      setState(() {
                          isrecord = true;
                      });
                      _changeTime(t);
                    }
                    MediaUtil.instance.stopRecordAudio((path, duration){
                      _file = File(path);
                    });
                    _stopTimer();
                  },
                  child: Padding(
                    padding: EdgeInsets.only(top: isselected ? 10 : 48),
                    child: isselected ? Image.asset("assets/huatong2.png") : Column(
                      children: [
                        Text(widget.noticelabel, textAlign: TextAlign.center, style: instanceTextStyle(10, APP_font_black),),
                        SizedBox(height: 10,),
                        Image.asset("assets/huatong1.png")
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
          Offstage(
            offstage: !isrecord,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 7),
                  margin: const EdgeInsets.only(top: 12),
                  decoration: BoxDecoration(
                    color: APP_main_color,
                    borderRadius: BorderRadius.circular(20)
                  ),
                  child: Text(voicestr, style: instanceTextStyle(14, Colors.white),),
                ),
                SizedBox(height: 10,),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 25),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      GestureDetector(
                        onTap: (){
                          voiceLength = 30;
                          _stopTimer();
                          _deleteFile();
                          setState(() {
                            isrecord = false;
                            isselected = false;
                            voicestr = "00:00";
                          });
                          MediaUtil.instance.stopPlayAudio();
                        },
                        child: Image.asset("assets/chogxin.png")
                      ),
                      GestureDetector(
                        onTap: (){
                          MediaUtil.instance.stopPlayAudio();
                          _stopTimer(); // 先停止再播放防止重复播放
                          MediaUtil.instance.startPlayAudio(_file.path);
                          _playTimer(recordLength);
                        },
                        child: Image.asset("assets/bofang.png"),
                      ),
                      GestureDetector(
                        onTap: (){
                          MediaUtil.instance.stopPlayAudio();
                          if(widget.onRecordFinish != null) {
                            voiceLength = 30;
                            setState(() {
                              isrecord = false;
                              isselected = false;
                              voicestr = "00:00";
                            });
                            widget.onRecordFinish(MediaUtil.instance.getCorrectedLocalPath(_file.path), recordLength);
                          }
                        },
                        child: Image.asset("assets/wancheng.png")
                      ),
                    ],
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}